package com.zhuhjay.framework.listener;

import com.corundumstudio.socketio.SocketIOServer;
import com.zhuhjay.common.netty.handler.AbstractSocketHandler;
import com.zhuhjay.common.redis.util.RedisUtils;
import com.zhuhjay.service.system.event.UserOfflineEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

import static com.zhuhjay.common.base.constant.CacheConstant.USER_ONLINE_PREFIX;
import static com.zhuhjay.common.base.constant.CacheConstant.USER_UNIQUE_ID_PREFIX;

/**
 * 用户下线监听器
 *
 * @author ZhuHJay
 * @date 2023/7/12 10:38
 */
@Component
public class UserOfflineListener {

    @Resource
    private SocketIOServer socketServer;

    @Async
    @EventListener(UserOfflineEvent.class)
    public void onUserOffline(UserOfflineEvent event) {
        String username = event.getUsername();
        if (event.getUid() == null) {
            // 下线所有客户端
            Set<String> uids = RedisUtils.getMembers4Set(USER_ONLINE_PREFIX + username);
            RedisUtils.deleteCache(USER_ONLINE_PREFIX + username);
            uids.forEach(uid -> {
                RedisUtils.deleteCache(USER_UNIQUE_ID_PREFIX + uid);
                // 将socket连接关闭
                if (AbstractSocketHandler.UID_SESSION_MAPPING.containsKey(uid)) {
                    socketServer.getClient(AbstractSocketHandler.UID_SESSION_MAPPING.get(uid)).disconnect();
                    AbstractSocketHandler.UID_SESSION_MAPPING.remove(uid);
                }
            });
        } else {
            // 下线指定客户端
            String uid = event.getUid();
            RedisUtils.deleteCache(USER_UNIQUE_ID_PREFIX + uid);
            RedisUtils.removeValue4Set(USER_ONLINE_PREFIX + username, uid);
            // 将socket连接关闭
            if (AbstractSocketHandler.UID_SESSION_MAPPING.containsKey(uid)) {
                socketServer.getClient(AbstractSocketHandler.UID_SESSION_MAPPING.get(uid)).disconnect();
                AbstractSocketHandler.UID_SESSION_MAPPING.remove(uid);
            }
        }
    }

}
